# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os
import sys

from .util import ensurePath, ensureFile, checkFile, md5

class Ensure(object):
    """docstring for Ensure"""
    def __init__(self, app, extra_config):
        super(Ensure, self).__init__()
        self.app = app
        self.extra_config = extra_config

    def ensureFS(self):
        # 确保所需文件夹存在
        ensurePath(self.extra_config.LOG_FOLDER)
        ensurePath(self.extra_config.STORE_IMAGE_FOLDER)
        # 确保所需文件存在
        ensureFile(self.extra_config.SERVER_VERSION_FILE)
        ensureFile(self.extra_config.SERVER_SECRET_FILE)
        # 确保版本号存在
        _version = self.getServerVersion()
        if _version is None or not isinstance(_version, int) and _version < 1:
            with open(self.extra_config.SERVER_VERSION_FILE, 'w') as f:
                f.write('1') # 默认最初版本号为1
        # 确保secret文件存在
        _secret = self.getServerSecret()
        _secret = self._checkSecret(_secret)
        with open(self.extra_config.SERVER_SECRET_FILE, 'w') as f:
            f.write(_secret)

    def getServerVersion(self):
        server_version = None
        with open(self.extra_config.SERVER_VERSION_FILE, 'r') as f:
            _value = f.read().strip()
            if _value.isdigit():
                server_version = int(_value)
        return server_version

    def ensureVersion(self):
        _version = self.getServerVersion()
        if _version is None or not isinstance(_version, int) and _version < 1:
            _version = 1
        self.app.config['server_version'] = _version

    def getServerSecret(self):
        server_secret = None
        if sys.version_info.major > 2:
            # http://stackoverflow.com/questions/12468179/unicodedecodeerror-utf8-codec-cant-decode-byte-0x9c
            f = open(self.extra_config.SERVER_SECRET_FILE, 'r', encoding='utf-8', errors='ignore')
        else:
            f = open(self.extra_config.SERVER_SECRET_FILE, 'r')
        server_secret = f.read().strip()
        f.close()
        return server_secret

    def _checkSecret(self, _secret):
        if not bool(_secret):
            _secret = str(os.urandom(24))
            _secret = md5(_secret)
            _secret = _secret[:24]
        return _secret
    def ensureSecret(self):
        _secret = self.getServerSecret()
        _secret = self._checkSecret(_secret)
        self.app.config['SECRET_KEY'] = _secret
        self.app.config['SECURITY_SALT'] = _secret[::2][:7] + _secret[::-2][:8]

    def ensureAll(self):
        self.ensureFS()
        self.ensureVersion()
        self.ensureSecret()